<template>
  <div id="feedback">
    <van-nav-bar
        title="bug反馈"
        left-text="返回"
        left-arrow
        @click-left="onClickLeft"
    />
    <div class="top">
      <van-cell-group inset>
        <van-field
            v-model="message"
            rows="8"
            autosize
            label="反馈"
            type="textarea"
            maxlength="100"
            placeholder="请输入反馈"
            show-word-limit
        />
      </van-cell-group>
    </div>
    <p class="tip">请上传图片</p>
    <div class="pic">
      <van-uploader
          v-model="imgList"
          multiple
          :max-count="5"
          deletable
      />
    </div>
    <div class="btn-box">
      <van-button class="btn" type="primary" size="large" @click="submit">提交反馈</van-button>

    </div>

  </div>
</template>

<script>
import {ref, reactive, toRefs} from 'vue';
import {Field, CellGroup, Toast, Uploader, Button,NavBar} from 'vant'
import {uploadImage} from "../../utils/uploadImage";
import {submitFeedback} from "@/api/submitFeedback.js"

export default {
  name: "FeedBack",
  components: {
    [Field.name]: Field,
    [CellGroup.name]: CellGroup,
    [Toast.name]: Toast,
    [Uploader.name]: Uploader,
    [Button.name]: Button,
    [NavBar.name]: NavBar
  },
  setup() {
    const state = reactive({
      imgList: [],
      message: ''
    })
    /**
     * 上传图片数组
     */
    const uploadFile = async list => {
      const fileList = [];
      for (let i = 0; i < list.length; i++) {
        try {
          const {url} = await uploadImage(list[i].file.name, list[i].file);
          fileList.push(url);
        } catch (error) {
          Toast("上传失败");
        }
      }
      return Promise.resolve(fileList);
    }
    const submit = async () => {
      console.log(state.imgList);
      const res = await uploadFile(state.imgList);
      if(state.message === ''){
        Toast.fail('你还没有填写反馈呢～')
        return
      }
      const params = {
        username: sessionStorage.getItem('username'),
        feedback: state.message,
        imgs: res
      };
      submitFeedback(params).then(res => {
        Toast.success({
          message:res.msg,
          forbidClick:true,
          onClose:function(){
            history.back();
          }
        });
      });
    }
    const onClickLeft = () => {
      history.back();
    }
    return {
      ...toRefs(state),
      submit,
      uploadFile,
      onClickLeft
    };
  }
}
</script>

<style lang="less" scoped>
#feedback {
  .top {
    padding-top: 20px;
  }
  .tip{
    font-size: 16px;
    text-align: left;
    padding-left: 20px;
  }
  .pic {
    padding: 15px;
    height: 200px;
  }

  .btn-box {
    position: fixed;
    left: 0;
    bottom: 0;
    width: 100%;
  }
}
</style>